import Flutter
import UIKit
import NetworkExtension

/**
 * VPN 插件 - iOS 平台实现
 * 提供与 V2Ray/Xray 核心的交互接口
 */
public class VpnPlugin: NSObject, FlutterPlugin {
    
    private var vpnManager: NEVPNManager?
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "com.fimuer.vpn/core", binaryMessenger: registrar.messenger())
        let instance = VpnPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "startXray":
            if let args = call.arguments as? [String: Any],
               let config = args["config"] as? String {
                startXray(config: config, result: result)
            } else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Config is required", details: nil))
            }
            
        case "stopXray":
            stopXray(result: result)
            
        case "getTrafficStats":
            getTrafficStats(result: result)
            
        case "prepareVpn":
            prepareVpn(result: result)
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    /**
     * 准备 VPN（加载配置）
     */
    private func prepareVpn(result: @escaping FlutterResult) {
        NEVPNManager.shared().loadFromPreferences { error in
            if let error = error {
                print("Failed to load VPN preferences: \(error.localizedDescription)")
                result(false)
            } else {
                result(true)
            }
        }
    }
    
    /**
     * 启动 Xray 核心
     */
    private func startXray(config: String, result: @escaping FlutterResult) {
        // 1. 写入配置文件
        guard let configData = config.data(using: .utf8) else {
            result(FlutterError(code: "ENCODING_ERROR", message: "Failed to encode config", details: nil))
            return
        }
        
        let fileManager = FileManager.default
        guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
            result(FlutterError(code: "FILE_ERROR", message: "Cannot access documents directory", details: nil))
            return
        }
        
        let configURL = documentsURL.appendingPathComponent("xray_config.json")
        
        do {
            try configData.write(to: configURL)
            print("Config written to: \(configURL.path)")
        } catch {
            result(FlutterError(code: "WRITE_ERROR", message: "Failed to write config: \(error.localizedDescription)", details: nil))
            return
        }
        
        // 2. 配置 VPN
        NEVPNManager.shared().loadFromPreferences { [weak self] error in
            if let error = error {
                result(FlutterError(code: "LOAD_ERROR", message: "Failed to load preferences: \(error.localizedDescription)", details: nil))
                return
            }
            
            self?.configureVPN(configPath: configURL.path, result: result)
        }
    }
    
    /**
     * 配置 VPN 设置
     */
    private func configureVPN(configPath: String, result: @escaping FlutterResult) {
        let vpnManager = NEVPNManager.shared()
        
        // 配置 VPN 协议
        let protocolConfig = NETunnelProviderProtocol()
        protocolConfig.providerBundleIdentifier = "com.example.flutter-vpn.VpnExtension" // 需要创建 Network Extension
        protocolConfig.serverAddress = "127.0.0.1" // 本地代理
        protocolConfig.providerConfiguration = ["config_path": configPath]
        
        vpnManager.protocolConfiguration = protocolConfig
        vpnManager.localizedDescription = "Fimuer VPN"
        vpnManager.isEnabled = true
        
        // 保存配置
        vpnManager.saveToPreferences { error in
            if let error = error {
                result(FlutterError(code: "SAVE_ERROR", message: "Failed to save VPN config: \(error.localizedDescription)", details: nil))
                return
            }
            
            // 启动 VPN
            do {
                try vpnManager.connection.startVPNTunnel()
                print("VPN started successfully")
                result(true)
            } catch {
                result(FlutterError(code: "START_ERROR", message: "Failed to start VPN: \(error.localizedDescription)", details: nil))
            }
        }
    }
    
    /**
     * 停止 Xray 核心
     */
    private func stopXray(result: @escaping FlutterResult) {
        let vpnManager = NEVPNManager.shared()
        vpnManager.connection.stopVPNTunnel()
        print("VPN stopped successfully")
        result(true)
    }
    
    /**
     * 获取流量统计
     */
    private func getTrafficStats(result: @escaping FlutterResult) {
        // 从 VPN Manager 获取流量统计
        let stats: [String: Int] = [
            "uploadSpeed": 0,
            "downloadSpeed": 0,
            "totalUpload": 0,
            "totalDownload": 0
        ]
        result(stats)
    }
}
